﻿using DadayunApi.BLL;
using KhtApi.BLL;
using KhtApi.Model;
using KhtMaintain.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KhtMaintain
{
    public partial class FrmPMC : Form
    {
        MainForm mainForm;
        private ReportBLL reportBLL;
        private FormBLL pmcBLL;
        string logUser;
        BindingList<ProductOrder> bProductOrderList = new BindingList<ProductOrder>();
        public FrmPMC(DadayunApi.Model.AppAuthBase authBase, string baseUri)
        {
            InitializeComponent();
            reportBLL = new ReportBLL(authBase, baseUri);
            pmcBLL = new FormBLL(authBase, baseUri);
            UserInfoBLL bll = new UserInfoBLL(authBase, baseUri);
            var login = bll.GetLoginInfo();
            logUser = login.User.Name;
        }

        private void FrmPMC_Load(object sender, EventArgs e)
        {
            string ver = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            mainForm = Tag as MainForm;
            mainForm.SetTitle($"PMC外挂器{ver}");
            mainForm.SetStaInfo("本外挂器与原系统兼容，但支持一次分解自产、外购、托工订单");
            tpTo.Value = DateTime.Now;
            tpStart.Value = tpTo.Value.AddDays(-7);

            dgvMaterials.AutoGenerateColumns = false;
            dgvSO.AutoGenerateColumns = false;
            dgvSO.DataSource = bProductOrderList;
            dgvMaterials.DataSource=bPmcMeterials;
        }

        private void BtnQuery_Click(object sender, EventArgs e)
        {
           var soBills=  reportBLL.GetSoBillBoards(tpStart.Value, tpTo.Value,chkExcludePlaned.Checked);
            IList<ProductOrder> ilist = ProductOrder.FromSoBillboard(soBills,reportBLL);
            bProductOrderList = new BindingList<ProductOrder>(ilist);
            dgvSO.DataSource = bProductOrderList;
            dgvSO.Refresh();

            IEnumerable<string> sales = soBills.Select(s => s.Saler).Distinct();
            cbSaler.Items.AddRange(sales.ToArray());
            IEnumerable<string> customers = soBills.Select(s => s.CusName).Distinct();
            cbCustom.Items.AddRange(customers.ToArray());
            bPmcMeterials.Clear();
            mainForm.SetStaInfo("订单调入完成");
        }

        private void BtnFilter_Click(object sender, EventArgs e)
        {
            IEnumerable<ProductOrder> selOrders = null;
            if(!string.IsNullOrEmpty( cbCustom.Text)&& !string.IsNullOrEmpty(cbSaler.Text))
            {
                selOrders = bProductOrderList.Where(s => s.CusName == cbCustom.Text && s.Saler == cbSaler.Text).ToList();
            }
            else if(!string.IsNullOrEmpty(cbCustom.Text))
            {
                selOrders = bProductOrderList.Where(s => s.CusName == cbCustom.Text).ToList();
            }
            else if (!string.IsNullOrEmpty(cbSaler.Text))
            {
                selOrders = bProductOrderList.Where(s => s.Saler == cbSaler.Text).ToList();
            }
            bProductOrderList = new BindingList<ProductOrder>(selOrders.ToList());
            dgvSO.DataSource = null;
            dgvSO.DataSource = bProductOrderList;
            
        }
        BindingList<PmcMaterial> bPmcMeterials = new BindingList<PmcMaterial>();
        List<PmcProduct> pmcProducts = new List<PmcProduct>();
        private void BtnDoPmc_Click(object sender, EventArgs e)
        {
            btnCommit.Enabled = false;
            Cursor = Cursors.WaitCursor;
            ProductOrder product = bProductOrderList[dgvSO.CurrentRow.Index];
            pmcProducts.Add(product.ToPmcProduct());
            pmcBLL.DoPMC( product.ItemCode, product.ItemCode, product.TotalQty, product.SoNo,ref bPmcMeterials,  Convert.ToDouble(product.Version));
            
            dgvMaterials.Refresh();
            mainForm.SetStaInfo("分解完成! "+pmcBLL.ErrMsg );
            if (!string.IsNullOrEmpty(pmcBLL.ErrMsg))
            {
                MessageBox.Show(pmcBLL.ErrMsg,"PMC返回信息",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            btnCommit.Enabled = true;
            Cursor = Cursors.Default;
        }
        private void BtnBatchPmc_Click(object sender, EventArgs e)
        {
            btnCommit.Enabled = false;
            Cursor = Cursors.WaitCursor;

            foreach (DataGridViewRow r in dgvSO.SelectedRows)
            {
                ProductOrder product = bProductOrderList[r.Index];
                pmcProducts.Add(product.ToPmcProduct());
                pmcBLL.DoPMC( product.ItemCode, product.ItemCode, product.TotalQty, product.SoNo, ref bPmcMeterials, Convert.ToDouble(product.Version));
            }

            dgvMaterials.Refresh();
            mainForm.SetStaInfo("批量分解完成!返回信息：" + pmcBLL.ErrMsg);
            btnCommit.Enabled = true;
            Cursor = Cursors.Default;
        }

        private void CbSaler_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnFilter.Enabled = (!string.IsNullOrEmpty(cbCustom.Text) || !string.IsNullOrEmpty(cbSaler.Text));
        }

        private void CbCustom_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnFilter.Enabled = (!string.IsNullOrEmpty(cbCustom.Text) || !string.IsNullOrEmpty(cbSaler.Text));
        }

        private void BtnCommit_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            var ans = pmcBLL.CreatePmcForm(bPmcMeterials, pmcProducts, logUser);
            if (ans )
            {
                mainForm.SetStaInfo("提交成功！");
                MessageBox.Show("提交成功！","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
            else
            {
                mainForm.SetStaInfo("提交失败!");
                MessageBox.Show("提交失败，返回信息为"+pmcBLL.ResponseJson,"错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }
            Cursor = Cursors.Default;
            btnCommit.Enabled = false;
        }

       

        private void DgvSO_SelectionChanged(object sender, EventArgs e)
        {
            if(dgvSO.SelectedRows.Count>0)
            {
                btnBatchPmc.Enabled = true;
                btnDoPmc.Enabled = true;
            }
            else
            {
                btnBatchPmc.Enabled = false;
                btnDoPmc.Enabled = false;
            }
            
        }

        private void DgvMaterials_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e)
        {
            //btnCommit.Enabled = dgvMaterials.Rows.Count > 0;
        }

        private void DgvMaterials_SelectionChanged(object sender, EventArgs e)
        {
            //if (dgvMaterials.CurrentRow.Index < 0) return;
        }

        private void DgvSO_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            
        }

        private void DgvMaterials_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            btnCommit.Enabled = dgvMaterials.Rows.Count > 0;
        }

        private void BtnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void BtnClear_Click(object sender, EventArgs e)
        {
            bPmcMeterials.Clear();
        }

        private void ContexMenu_Opening(object sender, CancelEventArgs e)
        {

        }

        private void CmnDelRow_Click(object sender, EventArgs e)
        {
            bPmcMeterials.RemoveAt(dgvMaterials.CurrentRow.Index);
        }
    }
}
